<template>
  <el-form ref="form" :inline="inline" :model="form" :size="size" label-width="150px" :label-position="labelPosition" :rules="rules">
    <el-form-item v-for="item in fields" :key="item.prop" :label="item.label" :prop="item.prop">
      <form-element v-model="form[item.prop]" :element="item.element" :type="item.type" :placeholder="item.placeholder" />
    </el-form-item>
    <el-form-item size="large">
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import formElement from '../form-element/index'

/**
* 属性 fields 的类型
interface IField {
  prop: string, // 字段属性
  placeholder: string, // 占位文本
  type: string, // 表单元素类型
  element: string, // 表单节点
  label: string
}
**/

export default {
  components: {
    formElement
  },
  props: {
    fields: {
      required: true,
      type: Array // IField
    },
    width: {
      type: String,
      default: ''
    },
    inline: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: ''
    },
    labelPosition: {
      type: String,
      default: 'left'
    }
  },
  data: function() {
    return {
      form: this.fields.reduce((p, field) => {
        p[field.prop] = ''
        return p
      }, {}),
      rules: this.fields.filter((i) => {
        return i.rules
      }).reduce((p, c) => {
        p[c.prop] = c.rules
        return p
      }, {})
    }
  },
  methods: {
    to_toogle(e) {
      this.toogle = !this.toogle
    },
    onSubmit(e) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('my-form-sure', this.form)
        }
      })
    },
    onCancel() {
      this.$emit('my-form-cancel', this.form)
      this.reset()
    },
    reset() {
      this.fields.forEach((i) => {
        this.form[i.prop] = i.default || ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
